package com.fish.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fish.common.exception.BusinessException;
import com.fish.common.result.ResultCode;
import com.fish.dao.mapper.OrganizationMapper;
import com.fish.dao.mapper.TitleMapper;
import com.fish.dao.mapper.UserOrganizationMapper;
import com.fish.model.dto.TitleDTO;
import com.fish.model.entity.Organization;
import com.fish.model.entity.Title;
import com.fish.model.entity.UserOrganization;
import com.fish.model.vo.TitleVO;
import com.fish.service.TitleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 头衔服务实现类
 */
@Slf4j
@Service
public class TitleServiceImpl implements TitleService {
    
    @Autowired
    private TitleMapper titleMapper;
    
    @Autowired
    private OrganizationMapper organizationMapper;
    
    @Autowired
    private UserOrganizationMapper userOrganizationMapper;
    
    @Override
    public List<TitleVO> getAllTitles() {
        List<Title> titles = titleMapper.selectList(
            new LambdaQueryWrapper<Title>()
                .eq(Title::getStatus, 1)
                .orderByAsc(Title::getTitleLevel, Title::getOrderNum)
        );
        
        return titles.stream()
            .map(this::convertToVO)
            .collect(Collectors.toList());
    }
    
    @Override
    public List<TitleVO> getTitlesByOrgId(Long orgId) {
        LambdaQueryWrapper<Title> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(w -> w.eq(Title::getOrgId, orgId).or().isNull(Title::getOrgId));
        wrapper.eq(Title::getStatus, 1);
        wrapper.orderByAsc(Title::getTitleLevel, Title::getOrderNum);
        
        List<Title> titles = titleMapper.selectList(wrapper);
        
        return titles.stream()
            .map(this::convertToVO)
            .collect(Collectors.toList());
    }
    
    @Override
    public TitleVO getTitleById(Long id) {
        Title title = titleMapper.selectById(id);
        if (title == null) {
            throw new BusinessException(ResultCode.DATA_NOT_EXIST.getCode(), "头衔不存在");
        }
        return convertToVO(title);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public TitleVO createTitle(TitleDTO dto) {
        // 检查头衔编码是否已存在
        LambdaQueryWrapper<Title> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Title::getTitleCode, dto.getTitleCode());
        if (titleMapper.selectCount(wrapper) > 0) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "头衔编码已存在");
        }
        
        Title title = new Title();
        BeanUtil.copyProperties(dto, title);
        
        titleMapper.insert(title);
        log.info("创建头衔成功，头衔名称：{}", title.getTitleName());
        
        return convertToVO(title);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public TitleVO updateTitle(TitleDTO dto) {
        if (dto.getId() == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "头衔ID不能为空");
        }
        
        Title title = titleMapper.selectById(dto.getId());
        if (title == null) {
            throw new BusinessException(ResultCode.DATA_NOT_EXIST.getCode(), "头衔不存在");
        }
        
        // 检查头衔编码是否重复
        if (!title.getTitleCode().equals(dto.getTitleCode())) {
            LambdaQueryWrapper<Title> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Title::getTitleCode, dto.getTitleCode());
            wrapper.ne(Title::getId, dto.getId());
            if (titleMapper.selectCount(wrapper) > 0) {
                throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "头衔编码已存在");
            }
        }
        
        BeanUtil.copyProperties(dto, title, "id", "createTime", "createBy");
        titleMapper.updateById(title);
        
        log.info("更新头衔成功，头衔ID：{}", title.getId());
        return convertToVO(title);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTitle(Long id) {
        // 检查是否有用户使用该头衔
        LambdaQueryWrapper<UserOrganization> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserOrganization::getTitleId, id);
        wrapper.eq(UserOrganization::getStatus, 1);
        
        if (userOrganizationMapper.selectCount(wrapper) > 0) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "该头衔正在使用中，无法删除");
        }
        
        titleMapper.deleteById(id);
        log.info("删除头衔成功，头衔ID：{}", id);
    }
    
    /**
     * 转换为VO
     */
    private TitleVO convertToVO(Title title) {
        TitleVO vo = new TitleVO();
        BeanUtil.copyProperties(title, vo);
        
        // 获取组织名称
        if (title.getOrgId() != null) {
            Organization org = organizationMapper.selectById(title.getOrgId());
            if (org != null) {
                vo.setOrgName(org.getOrgName());
            }
        }
        
        return vo;
    }
}

